package com.neuronbit.businessflow.intellij.util;

import com.mxgraph.model.mxICell;
import com.neuronbit.businessflow.intellij.model.Call;
import com.neuronbit.businessflow.intellij.model.Flow;
import com.neuronbit.businessflow.intellij.model.JavaMethodTask;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * The type Cell utils.
 */
public class CellUtils {
    /**
     * Gets precedings of.
     *
     * @param x         the x
     * @param taskNames the task names
     * @param list      the list
     */
    public void getPrecedingsOf(mxICell x, Set<String> taskNames, List<Call> list) {
        if (null == x) {
            return;
        }
        int edgeCount = x.getEdgeCount();
        if (edgeCount <= 0) {
            return;
        }
        for (int i = 0; i < edgeCount; i++) {
            mxICell edgeAt = x.getEdgeAt(i);
            mxICell pre = edgeAt.getTerminal(true);
            if (pre == x || pre == null) {
                continue;
            }
            if (pre.getValue() instanceof JavaMethodTask) {
                JavaMethodTask task = ((JavaMethodTask) pre.getValue());
                if (task == null) {
                    return;
                }
                if (StringUtils.isEmpty(task.getName()) || !taskNames.contains(task.getName())) {
                    return;
                }
                Call callable = task.getCallable();
                if (null == callable) {
                    return;
                }
                list.add(callable);
            }
            getPrecedingsOf(pre, taskNames, list);
        }
    }

    /**
     * Gets flow.
     *
     * @param cell the cell
     * @return the flow
     */
    public Call getFlow(mxICell cell) {
        mxICell c = cell;
        while (c.getParent() != null) {
            if (c.getParent().getValue() instanceof Flow) {
                return (Call) c.getParent().getValue();
            }
            c = c.getParent();
        }

        return null;
    }
}
